import datetime

from flask import current_app
from apps.interface.models.interfacecase import InterfaceCase
from apps.interface.models.interfacecaseset import InterfaceCaseSet
from apps.interface.models.interfaceproject import InterfaceProject
from apps.interface.models.interfacetask import InterfaceTask
from apps.interface.util.email.SendEmail import SendEmail
from apps.interface.util.http_run import RunCase, TEMP_REPORT
from apps.interface.util.report.report import render_html_report
from library.api.redis import RedisLock
from library.api.db import t_redis
from library.api.tFlask import tflask
from public_config import REDIS_TASK_NAME, REDIS_TASK_QUEUE, REDIS_TASK_NUMBER
from concurrent.futures import ThreadPoolExecutor
from library.notification import notification
import json
from apps.task.settings import config


class CiTaskBusiness(object):

    @classmethod
    def run_task(cls, task_params):
        with ThreadPoolExecutor(max_workers=20) as poolExecutor:
            task = poolExecutor.submit(CiTaskBusiness.execute, params=task_params)
            current_app.logger.info(f'ci任务线程状态>>>{task.done()}')
            # task.add_done_callback(notification.send_notification(us_li, text))
            return {'msg': 'ci任务成功', 'status': 1, 'data': {}}

    @classmethod
    def execute(cls, params):
        project_id = params['interface_project_id']
        redis_lock = RedisLock(t_redis)
        project_uuid = redis_lock.acquire_lock(project_id)
        try:
            if project_uuid:  # 获取到redis锁
                task_total = t_redis.get(REDIS_TASK_NAME)  # 获取当前执行任务数量
                if task_total is None:
                    task_total = 0
                if int(task_total) > REDIS_TASK_NUMBER:  # 如果任务数大于REDIS_TASK_NUMBER
                    t_redis.lpush(REDIS_TASK_QUEUE, json.dumps(params))  # 加入定时任务队列
                    return
                t_redis.incr(REDIS_TASK_NAME, 1)  # 任务总数+1
                try:
                    app = tflask(config)  # 定时任务需要app上下文
                    with app.app_context():
                        current_app.logger.info('>>> task uuid {}'.format(project_uuid))
                        report = CiTaskBusiness.run_case(project_id)
                        project_data = InterfaceProject.query.filter_by(name=project_id,
                                                                        status=InterfaceProject.ACTIVE).first()
                        interface_task = InterfaceTask.query.filter(project_id=project_id,
                                                                    delete_status=InterfaceProject.ACTIVE).first()
                        if interface_task.send_address:
                            if TEMP_REPORT.find('/apps/interface') == -1:
                                report_path = TEMP_REPORT.replace('/util/report', '/apps/interface/util/report')
                            else:
                                report_path = TEMP_REPORT
                            task_to_address = interface_task.task_to_email_address.split(',')
                            file = render_html_report(report,
                                                      html_report_name='{}接口自动化测试报告'.format(
                                                          datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')),
                                                      html_report_template=r'{}/extent_report_template.html'.format(
                                                          report_path),
                                                      data_or_report=False)
                            s = SendEmail(interface_task.task_send_email_address, interface_task.email_password,
                                          task_to_address, file)
                            s.send_email(name=project_data.name, content=report)
                except Exception as e:
                    current_app.logger.error(str(e))
                t_redis.decr(REDIS_TASK_NAME, 1)  # 任务总数-1
        finally:
            if project_uuid:
                redis_lock.release_lock(project_id, project_uuid)  # 释放redis锁

    @classmethod
    def run_case(cls, interface_project_id):
        case_ids = []
        # 查询模块id
        _set_ids = [_set.id for _set in
                    InterfaceCaseSet.query.filter_by(project_id=interface_project_id,
                                                     status=InterfaceCaseSet.ACTIVE).order_by(
                        InterfaceCaseSet.num.asc()).all()]
        for set_id in _set_ids:
            for case_data in InterfaceCase.query.filter_by(
                    case_set_id=set_id, status=InterfaceCase.ACTIVE).order_by(InterfaceCase.num.asc()).all():
                case_ids.append(case_data.id)
        d = RunCase(interface_project_id)
        jump_res = d.run_case(d.get_case_test(case_ids))
        d.build_report(jump_res, case_ids)
        return json.loads(jump_res)
